In C++, function overriding is a feature of polymorphism that allows a derived class to provide a specific implementation for a function that is already declared in its base class. Function overriding is commonly used in inheritance scenarios to provide different behaviors for derived class objects while maintaining a common interface defined in the base class. To achieve function overriding, use virtual functions and the override keyword.
Here are the key concepts and steps for function overriding in C++:
To enable function overriding, declare a function in the base class as virtual. Virtual functions are defined in the base class but it can be overridden in derived classes to provide specialized implementations.
In a derived class, declare a function with the same name, parameters, and return type as the virtual function in the base class that want to override. use the override keyword to indicate that intend to override the function. This keyword helps catch errors at compile-time if the function signature does not match.
When call a virtual function on an object of a derived class through a base class pointer or reference, C++ uses late binding (also called dynamic binding or runtime polymorphism) to determine which version of the function to execute. Late binding allows the program to select the appropriate function implementation based on the actual type of the object, not the declared type of the pointer or reference. Here's an example demonstrating function overriding in C++:
#include <iostream>
class Shape {
public:
virtual void display() {
std::cout << "Shape" << std::endl;
}
};
class Circle : public Shape {
public:
void display() override {
std::cout << "Circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void display() override {
std::cout << "Rectangle" << std::endl;
}
};
int main() {
Shape* shapePtr = nullptr;
Circle circle;
Rectangle rectangle;
shapePtr = &circle;
shapePtr->display(); // Calls Circle's display function
shapePtr = &rectangle;
shapePtr->display(); // Calls Rectangle's display function
return 0;
}
question
question2